package zkclient;

import org.I0Itec.zkclient.ZkClient;

/**
 * Created by Lenovo on 2018/11/20.
 */
public abstract class ZkAbstrackLock implements ILock{
    private static final String CONNECT_ADDR = "10.1.66.76:2181";
    //连接超时时间
    private static final int CONNECTION_TIMEOUT = 2000;
    protected static String node = "/lock";
    protected ZkClient zkClient = null;

    public ZkAbstrackLock() {
        zkClient = new ZkClient(CONNECT_ADDR,CONNECTION_TIMEOUT);
    }

    public void lock() {
        if(tryLock()){
            System.out.println("=========获取到锁=============");
        }else{
            waitforLock();
            lock();
        }
    }

    public void unlock() {
        //由于创建的是临时节点，则关闭zk的连接，锁自动释放
        zkClient.close();
    }

    //试着获取锁
    protected abstract boolean tryLock();
    //等待获取锁
    protected abstract void waitforLock();
}
